package datastructure.tree;

/**
 * @Description:
 * @Author Ammar
 * @Create 2023/3/29 16:11
 */
public class TreeNode<E> {
    public E val;
    public TreeNode<E> left;
    public TreeNode<E> right;
    public TreeNode<E> parent;

    public TreeNode() {
    }

    public TreeNode(E val) {
        this(val, null);
    }

    public TreeNode(E val, TreeNode<E> parent) {
        this.val = val;
        this.parent = parent;
    }

    // 判断是否为叶子节点
    public boolean isLeaf() {
        return left == null && right == null;
    }

    // 判断是否为度为2的节点
    public boolean hasTwoChildren() {
        return left != null && right != null;
    }

    // 判断是否为左子节点
    public boolean isLeftChild() {
        return parent != null && this == parent.left;
    }

    // 判断是否为右子节点
    public boolean isRightChild() {
        return parent != null && this == parent.right;
    }

    // 返回兄弟节点
    public TreeNode<E> sibling() {
        if (isLeftChild()) {
            return parent.right;
        }
        if (isRightChild()) {
            return parent.left;
        }
        return null;
    }

    @Override
    public String toString() {
        String parentStr = "null";
        if (parent != null) {
            parentStr = parent.val.toString();
        }
        return val.toString();
    }
}
